package com.sword.springboot.service.impl;

import java.util.List;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sword.springboot.bean.User;
import com.sword.springboot.dao.UserMapper;
import com.sword.springboot.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	private String algorithmName = "MD5";
	private Integer hashIterations = 2;
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public User getUser(String username) {
		/*User user = new User();
		if(username!=null && username.equals("wang")){
			user.setId(1);
			user.setUsername(username);
			user.setPassword("123");
			user.setName("王");
		}*/
		User user = userMapper.selectUserByUsername(username);
		return user;
	}

	@Override
	public User getUser(Integer id) {
		User user = userMapper.selectUserById(id);
		return user;
	}

	@Override
	public Integer addNewUser(User user) throws Exception{
		//为每一个新用户生成一个随机盐
		SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
		//secureRandomNumberGenerator.setSeed(user.getUsername().getBytes()); //加种子后，随机数就固定了
		user.setSalt(secureRandomNumberGenerator.nextBytes().toHex());
		//加密
		String newWord = new SimpleHash(algorithmName, user.getPassword(), user.getSalt(), hashIterations).toHex();
		user.setPassword(newWord);
		//System.out.println("=================加密后密码："+newWord+",长度："+newWord.length()+",盐："+user.getSalt());
		//存入数据库
		Integer result = userMapper.saveUser(user);
		return result;
	}

	@Override
	public List<User> getUsers() throws Exception {
		return userMapper.selectUsers();
	}

}
